import { useRef } from 'react'
import { useMemoizedFn, useBoolean } from 'ahooks'

export const useNumChange = (num: number | string = 0) => {
  const [,{ toggle }] = useBoolean()
  const timer = useRef<NodeJS.Timeout>()
  const count = useRef<string>(String(num))
  const start = useMemoizedFn((e: number | string) => {
    if (timer.current) clearInterval(timer.current)

    const time = Number(e || count.current)
    count.current = Array(`${time}`.length).fill('0').join('')

    timer.current = setInterval(() => {

      let nowCount = Number(count.current)
      nowCount += Number((time / 30).toFixed(0))

      if (nowCount > time) {
        count.current = time.toString()
        clearInterval(timer.current)
        toggle()
      } else {
        const str = Array((`${time}`.length - `${nowCount}`.length)).fill('0').join('')
        count.current = `${str}${nowCount}`
        toggle()
      }
    }, 50)
  })

  return { count: count.current, start }
}
